package com.tanjie.blackbean.mybatis.query;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 查询条件构造器
 *
 * @author: tanjie
 * @date: 2021-12-14
 **/
public class Condition {

    /**
     * 转化成mybatis plus中的Page
     *
     * @param pageParam 查询条件
     * @return IPage
     */
    public static <T> IPage<T> getPage(PageParam pageParam) {
        if (pageParam == null) {
            return new Page<>(1, 10);
        }
        int current = pageParam.getCurrent() == null ? 1 : pageParam.getCurrent();
        int size = pageParam.getSize() == null ? 10 : pageParam.getSize();
        Page<T> page = new Page<>(current, size);
        StrUtil.split(pageParam.getAscs(), ",").forEach(s -> page.addOrder(OrderItem.asc(s)));
        StrUtil.split(pageParam.getDescs(), ",").forEach(s -> page.addOrder(OrderItem.desc(s)));
        return page;
    }

    public static void addDefaultOrder(IPage<?> page) {
        if (CollectionUtil.isEmpty(page.orders())) {
            page.orders().add(OrderItem.desc("update_time"));
        }
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param entity 实体
     * @param <T>    类型
     * @return QueryWrapper
     */
    public static <T> QueryWrapper<T> getQueryWrapper(T entity) {
        return new QueryWrapper<>(entity);
    }

}
